/**
 * 14/02/2014
 * 
 * StateDAO
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.State;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of StateDAO
 * @author Javier Tejedor
 */
public class StateDAO implements StateDAOInterface {

	@Autowired
	private SessionFactory sessionFactory;


	/**
	 * Constructor
	 */
	public StateDAO () {

	}

	/**
	 * returns Hibernate session
	 * @return
	 */
	private Session getSession () {
		return sessionFactory.getCurrentSession();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#selectById(int)
	 */
	@Transactional(readOnly = true)
	public State selectById(int id) {
		State state = (State) getSession().get(State.class, id);
		return state;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#selectAll()
	 */
	@Transactional(readOnly = true)
	public List<State> selectAll() {
		List<State> state = getSession().createQuery("from State").list();
		return state;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#selectAllCount()
	 */
	@Transactional(readOnly = true)
	public int selectAllCount() {
		List<State> state = getSession().createQuery("from State").list();
		return state.size();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#insert(org.cuatrovientos.erp.model.State)
	 */
	@Transactional
	public void insert(State state) {
		Integer id = (Integer) getSession().save(state);
		state.setId(id);           
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#update(org.cuatrovientos.erp.model.State)
	 */
	@Transactional
	public void update(State state) {
		getSession().merge(state);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#delete(org.cuatrovientos.erp.model.State)
	 */
	@Transactional
	public void delete(State state) {
		getSession().delete(state);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#saveOrUpdate(org.cuatrovientos.erp.model.State)
	 */
	@Transactional
	public void saveOrUpdate(State state) {
		getSession().saveOrUpdate(state);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#deleteById(int)
	 */
	@Transactional
	public void deleteById(int id) {
		State state = (State) getSession().load(State.class,id);
		getSession().delete(state);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.StateDAOInterface#search(java.lang.String)
	 */
	@Transactional(readOnly = true)
	public List<State> search(String name) {
		Query query = 
				getSession().
				createQuery("from State s where s.name like :name");
		
		query.setParameter("name", "%" + name + "%");

		List<State> state = query.list();

		return state;
	}

}
